package com.xuxingcan;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.File;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by xuxingcan on 2/22/16.
 */
public class WorkThread {
    private String analysisUrl, dirPath;
    private boolean isRunning = false;
    private File downloadingFile;
    private int fileSize = -1;

    public WorkThread() {
    }

    public void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                isRunning = true;
                String result = HttpUtil.get(HttpUtil.getFlvcdUrl(analysisUrl), "GB2312");
//                System.out.print(result);
                Document mDocument = Jsoup.parse(result);
                Elements mElements = mDocument.getElementsByAttributeValue("onclick", "_alert();return false;");
                if (mElements.size() == 0) {
                    return;
                }
                String downloadUrl = mElements.get(0).attr("href");
                mElements = mDocument.getElementsContainingOwnText("当前解析视频");
                String s = mElements.get(0).parent().html();
                if (mElements.size() == 0) {
                    return;
                }
                String fileName = s.substring(s.indexOf("</strong>") + "</strong>".length(), s.lastIndexOf("<strong>"));
                try {
                    downloadingFile = new File(dirPath, fileName + ".mp4");
                    URLConnection conn = new URL(downloadUrl).openConnection();
                    fileSize = conn.getContentLength();
                    if (downloadingFile.exists()) {
                        if (downloadingFile.length() == fileSize) {
                            System.out.println(fileName + " is alread downloaded!");
                        } else {
                            downloadingFile.delete();
                            FileUtil.downloadFile(downloadUrl, downloadingFile);
                        }
                    } else {
                        FileUtil.downloadFile(downloadUrl, downloadingFile);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                isRunning = false;
            }
        }).start();
    }

    public String getDownloadInfo() {
        if (downloadingFile == null) {
            return "wait a min.....";
        } else {
            return downloadingFile.getName() + " is at " + downloadingFile.length() / fileSize * 100 + "%";
        }
    }

    public boolean isRunning() {
        return isRunning;
    }

    public void setAnalysisUrl(String analysisUrl) {
        this.analysisUrl = analysisUrl;
    }

    public void setDirPath(String dirPath) {
        this.dirPath = dirPath;
    }
}
